package com.example.wx.dailyreport.controller.security;

import com.example.wx.dailyreport.pojo.User;
import com.example.wx.dailyreport.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;

@Component
public class SelfAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();


        User user = userService.findByUsername(username);

        if (user == null)
            //用户名不存在
            throw new BadCredentialsException("用户名不存在");
        if (user.getSurvival() == 0)
            //用户未激活
            throw new BadCredentialsException("用户未激活");
        if (!bCryptPasswordEncoder.matches(password, user.getPassword()))
            //密码错误
            throw new BadCredentialsException("密码错误");
        Set<GrantedAuthority> set = new HashSet<>();
        set.add(new SimpleGrantedAuthority("ROLE_" + ""));
        return new UsernamePasswordAuthenticationToken(username, password, set);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
